package com.circle.rest.core.aop;

import com.alibaba.fastjson.JSON;
import com.circle.rest.core.common.enums.BusinessStatus;
import com.circle.rest.core.common.enums.OperatorType;
import com.circle.rest.core.gmap.GMapTool;
import com.circle.rest.core.gmap.model.IpLocation;
import com.circle.rest.core.jwt.JwtUtil;
import com.circle.rest.core.manager.AsyncManager;
import com.circle.rest.core.manager.factory.AsyncFactory;
import com.circle.rest.core.util.ServletUtils;
import com.circle.rest.core.util.ToolUtil;
import com.circle.rest.modular.sys.model.OperLog;
import com.circle.rest.modular.sys.model.User;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * @program: 200221000010675
 * @description: Log切面
 * @author: 赵航
 * @create: 2019-03-07 11:33
 **/
@Aspect
@Component
public class LogAdvice {
    private static final Logger log = LoggerFactory.getLogger(LogAdvice.class);

    // 配置织入点
    @Pointcut("@annotation(com.circle.rest.core.aop.Log)")
    public void logPointCut() {
    }

    /**
     * 前置通知 用于拦截操作
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "logPointCut()")
    public void doBefore(JoinPoint joinPoint) {
        handleLog(joinPoint, null);
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint
     * @param e
     */
    @AfterThrowing(value = "logPointCut()", throwing = "e")
    public void doAfter(JoinPoint joinPoint, Exception e) {
        handleLog(joinPoint, e);
    }

    protected void handleLog(final JoinPoint joinPoint, final Exception e) {
        try {
            // 获得注解
            Log controllerLog = getAnnotationLog(joinPoint);
            if (controllerLog == null) {
                return;
            }
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            // 获取当前的用户
            User currentUser = JwtUtil.getUser(request);

            // *========数据库日志=========*//
            OperLog operLog = new OperLog();
            operLog.setStatus(BusinessStatus.SUCCESS.getCode());
            operLog.setBrowser(ToolUtil.getBrowser(request));
            // 请求的地址
            String ip = ToolUtil.getIpAddress(request);
            operLog.setOperIp(ip);
            if (ip.equals("0:0:0:0:0:0:0:1")
                    || ip.equals("127.0.0.1")) {
                operLog.setOperLocation("本机");
            } else {
                IpLocation ipLocation = GMapTool.getIpLocation(ip);
                String province = ipLocation.getProvince();
                String city = ipLocation.getCity();
                operLog.setOperLocation((province.equals("[]") ? "" : province)
                        + (city.equals("[]") ? "" : city));
            }

//            if (ToolUtil.internalIp(ip)) {
//                operLog.setOperLocation("公网IP");
//            } else {
//                operLog.setOperLocation("内网IP");
//            }


            operLog.setOperUrl(request.getRequestURL().toString());
            if (currentUser != null) {
                operLog.setOperName(currentUser.getLoginName());
                if (ToolUtil.isNotEmpty(currentUser.getDeptid())) {
                    //TODO 设置部门名称
//                    operLog.setDeptName(currentUser.getDept().getDeptName());
                }
            }

            if (e != null) {
                operLog.setStatus(BusinessStatus.FAIL.getCode());
                operLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
            }
            // 设置方法名称
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            operLog.setMethod(className + "." + methodName + "()");
            // 处理设置注解上的参数
            getControllerMethodDescription(controllerLog, operLog);
            // 设置日志操作时间
            operLog.setOperTime(LocalDateTime.now());

            if (operLog.getOperatorType() == OperatorType.OTHER.getCode()) {
                if (operLog.getBrowser().equals("Android") || operLog.getBrowser().equals("IOS")) {
                    operLog.setOperatorType(OperatorType.MOBILE.getCode());
                }
                if (operLog.getBrowser().equals("WindowsBS") || operLog.getBrowser().equals("LinuxBS")) {
                    operLog.setOperatorType(OperatorType.MANAGE.getCode());
                }
            }
            // 保存数据库
            AsyncManager.me().execute(AsyncFactory.recordOper(operLog));
        } catch (Exception exp) {
            // 记录本地异常日志
            log.error("==前置通知异常==");
            log.error("异常信息:{}", exp.getMessage());
            exp.printStackTrace();
        }
    }

    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     *
     * @param log     日志
     * @param operLog 操作日志
     * @throws Exception
     */
    public void getControllerMethodDescription(Log log, OperLog operLog) throws Exception {
        // 设置action动作
        operLog.setBusinessType(log.businessType().getCode());
        // 设置标题
        operLog.setTitle(log.title());
        // 设置操作人类别
        operLog.setOperatorType(log.operatorType().getCode());
        // 是否需要保存request，参数和值
        if (log.isSaveRequestData()) {
            // 获取参数的信息，传入到数据库中。
            setRequestValue(operLog);
        }
    }

    /**
     * 获取请求的参数，放到log中
     *
     * @param operLog 操作日志
     * @throws Exception 异常
     */
    private void setRequestValue(OperLog operLog) throws Exception {
        Map<String, String[]> map = ServletUtils.getRequest().getParameterMap();
        String params = JSON.toJSONString(map);
        operLog.setOperParam(StringUtils.substring(params, 0, 255));
    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private Log getAnnotationLog(JoinPoint joinPoint) throws Exception {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null) {
            return method.getAnnotation(Log.class);
        }
        return null;
    }
}
